from flask import Blueprint, request, jsonify
from ..function import scheduler, add_new_job, remove_job, get_all_jobs
from ..tasks import TASK_FUNCTIONS  # 导入任务函数映射表

bp = Blueprint('jobs', __name__)

# TASK_FUNCTIONS = {
#     "analyze_data_task": "app.Ai_analyze.ai_function.analyze_data_task",
#     "backup_database_task": "app.tasks.backup_database_task",
#     "cleanup_logs_task": "app.tasks.cleanup_logs_task",
#     "generate_report_task": "app.tasks.generate_report_task"
# }


@bp.route('/jobs', methods=['GET'])
def get_jobs():
    """获取所有定时任务"""
    try:
        jobs = get_all_jobs()
        jobs_data = []

        for job in jobs:
            # 获取触发器类型和参数
            trigger_type = type(job.trigger).__name__
            trigger_args = {}

            # 根据不同的触发器类型提取参数
            # if trigger_type == 'IntervalTrigger':
            #     trigger_args = {
            #         'weeks': job.trigger.weeks,
            #         'days': job.trigger.days,
            #         'hours': job.trigger.hours,
            #         'minutes': job.trigger.minutes,
            #         'seconds': job.trigger.seconds,
            #         'start_date': str(job.trigger.start_date) if job.trigger.start_date else None,
            #         'end_date': str(job.trigger.end_date) if job.trigger.end_date else None,
            #         'jitter': job.trigger.jitter
            #     }
            # elif trigger_type == 'CronTrigger':
            #     trigger_args = {
            #         'year': job.trigger.year,
            #         'month': job.trigger.month,
            #         'day': job.trigger.day,
            #         'week': job.trigger.week,
            #         'day_of_week': job.trigger.day_of_week,
            #         'hour': job.trigger.hour,
            #         'minute': job.trigger.minute,
            #         'second': job.trigger.second,
            #         'start_date': str(job.trigger.start_date) if job.trigger.start_date else None,
            #         'end_date': str(job.trigger.end_date) if job.trigger.end_date else None,
            #         'jitter': job.trigger.jitter
            #     }
            # elif trigger_type == 'DateTrigger':
            #     trigger_args = {
            #         'run_date': str(job.trigger.run_date),
            #         'timezone': str(job.trigger.timezone)
            #     }

            # 查找函数名
            func_name = next((name for name, func in TASK_FUNCTIONS.items() if func == job.func), job.func.__name__)

            job_data = {
                'id': job.id,
                'func': func_name,
                'trigger': trigger_type,
                'trigger_args': trigger_args,
                'active': not job.pending  # 任务是否活跃
            }
            jobs_data.append(job_data)

        return jsonify(jobs_data)
    except Exception as e:
        print(e)
        return jsonify({'error': '获取任务列表失败'}), 500

@bp.route('/jobs/add', methods=['POST'])
def add_job():
    """添加新定时任务"""
    data = request.json
    job_id = data.get('job_id')
    job_type = data.get('job_type')  # 'interval', 'cron', 'date'
    job_function = data.get('job_function')
    trigger_args = data.get('trigger_args', {})
    # 验证任务函数是否存在
    if job_function not in TASK_FUNCTIONS:
        return jsonify({'error': '无效的任务函数'}), 400

    try:
        add_new_job(job_id, TASK_FUNCTIONS[job_function], job_type, **trigger_args)
        return jsonify({'message': f'任务 {job_id} 添加成功'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/jobs/<job_id>', methods=['DELETE'])
def delete_job(job_id):
    """删除定时任务"""
    try:
        remove_job(job_id)
        return jsonify({'message': f'任务 {job_id} 已删除'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@bp.route('/jobs/<job_id>/toggle', methods=['POST'])
def toggle_job(job_id):
    """切换任务状态（启用/暂停）"""
    data = request.json
    active = data.get('active', True)

    try:
        job = scheduler.get_job(job_id)
        if not job:
            return jsonify({'error': '任务不存在'}), 404

        if active:
            scheduler.resume_job(job_id)
        else:
            scheduler.pause_job(job_id)

        return jsonify({'message': f'任务 {job_id} 状态已更新'})
    except Exception as e:
        return jsonify({'error': str(e)}), 500